/**
 * 定义事件总线
 * 这里暂时用在scrollView滚动事件由父组件向子组件传递
 * 如果通过setState传递，其他组件需要编写shouldComponentUpdate
 * 来避免不必要的渲染过程
 */

const subscribes = {};
const throttle = function(fn, delay) {
  let applyTime = 0;

  return function(...args) {
    const context = this;
    const now = Date.now();
    if (!applyTime || now - applyTime > delay) {
      applyTime = now;
      fn.apply(context, args);
    }
  };
};
export const eventBus = {
  $emit: throttle((type, value) => {
    if (subscribes[type]) {
      subscribes[type].forEach(fn => {
        // 节流处理
        fn(value);
      });
    }
  }, 30),
  $on: (type, callback) => {
    if (!subscribes[type]) {
      subscribes[type] = [];
    }
    subscribes[type].push(callback);
  },
};

export default {};
